package com.naiterui.ehp.bp.support.message;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.ClassUtils;

/**
 * 抽象的message资源加载器
 *
 * @author zhouyanxin
 * @since 1.0.0
 */
public abstract class AbstractMessageLoader implements InitializingBean {

    private static final Logger LOGGER = LoggerFactory.getLogger(AbstractMessageLoader.class);

    /**
     * 资源持有器
     */
    private MessageHolder messageHolder = MessageHolder.getInstance();

    /**
     * 从properties资源文件中加载message资源
     * AbstractMessageLoader.loadMessageAsProperties()
     *
     * @param path
     *
     * @return
     *
     * @Author zhouyanxin
     * @Date 2017年11月10日
     * @since 1.0.0
     */
    protected Properties loadMessageAsProperties(String path) {

        try (InputStream resourceAsStream = ClassUtils.getDefaultClassLoader().getResourceAsStream(path)) {
            if (resourceAsStream == null) {
                LOGGER.warn("business not file {}", path);
                return null;
            }
            try (Reader reader = new InputStreamReader(resourceAsStream, "UTF-8")) {
                Properties properties = new Properties();
                properties.load(reader);
                return properties;
            }
        } catch (IOException e) {
            LOGGER.error("load message from properties {} failed", path, e);
            return null;
        }
    }

    /**
     * 从properties中解析message资源
     * AbstractMessageLoader.resloveMessageFromProperties()
     *
     * @param properties
     *
     * @Author zhouyanxin
     * @Date 2017年11月10日
     * @since 1.0.0
     */
    protected void resloveMessageFromProperties(Properties properties) {
        if (properties != null) {
            for (Object o : properties.keySet()) {
                String key = (String) o;
                this.messageHolder.addMessage(Integer.valueOf(key), properties.getProperty(key));
            }
        }
    }
}
